package com.googlecode.gwt.test.plugin.editors;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.texteditor.ITextEditor;

public class CustomKeyWordHyperLink implements IHyperlink {

	private IProject currentProject;
	private String rootKeyWord;
	private IRegion fRegion;

	public CustomKeyWordHyperLink(IRegion region, String rootKeyWord, IProject currentProject) {
		this.fRegion = region;
		this.rootKeyWord = rootKeyWord;
		this.currentProject = currentProject;
	}

	@Override
	public IRegion getHyperlinkRegion() {
		return this.fRegion;
	}

	@Override
	public String getHyperlinkText() {
		return this.rootKeyWord;
	}

	@Override
	public String getTypeLabel() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void open() {
		IType type;
		try {
			type = ProjectPluginProperty.getInstance().getCustomKeyWordsResource(currentProject).getType(rootKeyWord);
			IFile file = currentProject.getFile(type.getResource().getProjectRelativePath());
			IEditorPart editorPart = IDE.openEditor(Workbench.getInstance().getActiveWorkbenchWindow().getActivePage(), file, true);
			ITextEditor editor = (ITextEditor) editorPart;
			IMethod meth = getMethodByNameOnly(type, rootKeyWord);
			if (meth != null) {
				ISourceRange rang = meth.getSourceRange();
				editor.selectAndReveal(rang.getOffset(), 0);
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private IMethod getMethodByNameOnly(IType type, String rootKeyWord) throws JavaModelException {
		IMethod[] methods = type.getMethods();
		for (IMethod m : methods) {
			if (rootKeyWord.equals(m.getElementName())) {
				return m;
			}
		}
		return null;
	}
}
